﻿using AutoMapper;
using Core.SimpleTemp.Application.RoleApp;
using Core.SimpleTemp.Application.SysApp.UserApp.Dto;
using Core.SimpleTemp.Application.UserApp;
using Core.SimpleTemp.Common;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.SimpleTemp.Repositories.RepositoryEntityFrameworkCore.Sys;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Mvc.Api.Sys
{
    /// <summary>
    /// 用户信息
    /// </summary>
    [ApiExplorerSettings(GroupName = "Sys")]
    [Route("api/[controller]")]
    [EnableCors("any")]
    [ApiController]
    [Authorize]
    public class UserController : CoreApiController
    {
        private readonly SysUserAppService _service;

        private readonly ILogger<UserController> _logger;

        private readonly SysUserRepository _repository;
        WebAppOptions _webAppOptions;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="service"></param>
        /// <param name="sysRoleAppService"></param>
        /// <param name="logger"></param>
        /// <param name="webAppOptions"></param>
        public UserController(SysUserAppService service, SysRoleAppService sysRoleAppService, ILogger<UserController> logger, IOptionsMonitor<WebAppOptions> webAppOptions, SysUserRepository repository)
        {
            _service = service;
            _logger = logger;
            _webAppOptions = webAppOptions.CurrentValue;
            var a = AppDomain.CurrentDomain.BaseDirectory;
            _repository = repository;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>
        [HttpPost("GetList")]
        [PermissionFilter(nameof(UserController) + "_" + nameof(UserController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult> GetList(PagingModel<SysUserDto> pagingQueryModel)
        {
            IPageModel<SysUserDto> result = null;
            result = await _service.GetList(pagingQueryModel);
            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>
        [HttpPost("Export")]
        public async Task<IActionResult> Export(PagingModel<SysUserDto> pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            return this.JsonSuccess(fileName);
        }

        /// <summary>
        /// 增/改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(UserController) + "_" + nameof(UserController.SaveAsync), AuthorizationConst.SAVE)]

        public async Task<IActionResult> SaveAsync(SysUserDto dto)
        {
            dto.SysUserInfor.Name = dto.Name;//Name冗余到UserInfo中
            //添加
            if (Equals(dto.Id, Guid.Empty))
            {
                var model = await _service.VerifyLoginName(dto.LoginName);
                if (model != null)
                    return this.JsonFaild($"登录名{dto.LoginName}以存在");

                await _service.InsertAsync(dto, false);
                return this.JsonSuccess(string.Empty);
            }
            else
            {
                await _service.UpdateAsync(dto, true, new List<string>() { nameof(SysUser.Password), nameof(SysUser.LoginName) });
                return this.JsonSuccess(string.Empty);
            }
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(UserController) + "_" + nameof(UserController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult> DeleteMutiAsync([FromBody]Guid[] ids)
        {
            #region 验证是否是admin
            var retDleteVerifyAdmin = await DleteVerifyAdmin(ids);
            if (retDleteVerifyAdmin != null)
                return retDleteVerifyAdmin;
            #endregion
            await _service.DeleteBatchAsync(ids);
            return this.JsonSuccess();
        }

        /// <summary>
        /// 根据ID获取用户信息
        /// </summary>
        /// <param name="id">Guid</param>
        /// <returns></returns>
        [HttpGet("Get")]
        [PermissionFilter(nameof(UserController) + "_" + nameof(UserController.Get), AuthorizationConst.GET)]
        public async Task<IActionResult> Get(Guid id)
        {
            var model = await _service.GetAsync(id);
            var dto = Mapper.Map<SysUserDto>(model);

            return this.JsonSuccess(model);
        }

        /// <summary>
        /// 删除时验证用户是否是admin
        /// </summary>
        /// <param name="delIds">删除用户信息</param>
        /// <returns></returns>
        private async Task<IActionResult> DleteVerifyAdmin(Guid[] delIds)
        {
            Guid adminId = Guid.Empty;
            var admin = await _service.GetListAsync(u => u.LoginName == _webAppOptions.AdminLoginName);
            if (admin != null && admin.Any())
            {
                adminId = (Guid)admin.FirstOrDefault()?.Id;
                if (delIds.Contains(adminId))
                {
                    return this.JsonFaild($"{_webAppOptions.AdminLoginName}用户不能删除");
                }
            }
            return null;
        }

        /// <summary>
        /// 验证用户名
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        [HttpGet("VerifyLoginName")]
        public async Task<IActionResult> VerifyLoginName(string loginName)
        {
            var model = await _service.VerifyLoginName(loginName);
            if (model != null)
                return this.JsonFaild($"登录名{loginName}以存在");
            else
                return this.JsonSuccess(model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("UpdatePwd")]
        public async Task<IActionResult> UpdatePwd(UpdatePwdDto dto)
        {
            dto.LoginName = UserIdentity.LoginName;
            var isSuccess = await _service.UpdatePwdAsync(dto);
            if (isSuccess)
                return this.JsonSuccess();
            else
                return this.JsonFaild("操作失败");
        }

        #region 用户部门职务
        /// <summary>
        /// 根据ID获取用户信息及部门职务信息
        /// </summary>
        /// <param name="id">Guid</param>
        /// <returns></returns>
        [HttpGet("GetUserDuty")]
        [PermissionFilter(nameof(UserController) + "_" + nameof(UserController.GetUserDuty), "获取用户职务信息")]
        public async Task<IActionResult> GetUserDuty(Guid id)
        {

            var userModel = await _service.GetAsync(id);
            List<SysUserDuty> list = await _service.GetUserDutyAsync(id);
            var dutyList = list.Select(sud => new
            {
                DepartDutyId = sud.SysDepartmentDutyId,
                DepartmentName = sud.SysDepartmentDuty.SysDepartment.Name,
                DepartmentId = sud.SysDepartmentDuty.SysDepartment.Id,
                DutyName = sud.SysDepartmentDuty.SysDuty.Name,
                DutyId = sud.SysDepartmentDuty.SysDuty.Id,
                sud.Id
            });

            var returnModel = new { userModel.LoginName, UserName = userModel.Name, dutyList };
            return this.JsonSuccess(returnModel);
        }

        /// <summary>
        ///  获取当前用户部门信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("Department")]
        public async Task<IActionResult> Department()
        {
            var department = await _service.UserDepartmentAsync(UserIdentity.Id);
            var returnModel = department.Select(a => new { a.Id, a.Name });
            return this.JsonSuccess(returnModel);
        }


        /// <summary>
        /// 删除职务信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteDutyMuti")]
        [PermissionFilter(nameof(UserController) + "_" + nameof(UserController.DeleteDutyMutiAsync), "删除职务信息")]
        public async Task<IActionResult> DeleteDutyMutiAsync([FromBody]Guid[] ids)
        {
            await _service.DeleteDutyBatchAsync(ids);

            return this.JsonSuccess();
        }

        /// <summary>
        /// 修改职务分配 
        ///</summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        [HttpPost("SaveUserDuty")]
        [PermissionFilter(nameof(UserController) + "_" + nameof(UserController.SaveUserDutyAsync), "保存用户职务分配")]
        public async Task<IActionResult> SaveUserDutyAsync(UpdateUserDutyModel dtos)
        {
            List<SysUserDutyDto> list = new List<SysUserDutyDto>();
            foreach (var item in dtos.DepartmenDutytId)
            {
                var dd = _repository._dbContext.SysDepartmentDuty.FirstOrDefault(x => x.Id == item);
                list.Add(new SysUserDutyDto
                {
                    SysUserId = dtos.UserId,
                    SysDepartmentDutyId = item,
                    SysDutyID = dd.SysDutyID
                });
            }
            await _service.UpdateUserDutyAsync(dtos.UserId, list);
            return this.JsonSuccess();
        }
        #endregion

        /// <summary>
        /// 获取当前用户签名信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("Signature")]
        public async Task<IActionResult> Signature()
        {
            var user = await _service.GetAsync(UserIdentity.Id);
            return this.JsonSuccess(new
            {
                user.SysUserInfor.SignID,
                user.SysUserInfor.SignPath
            });
        }





    }
}